package com.aispeech.task.common.data;

import com.aispeech.task.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public abstract class AbstractForm {
    public Map<String, Object> toMap() {
        Map<String, Object> map = new HashMap<>();

        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(this.getClass(), Object.class);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                String key = propertyDescriptor.getName();
                Method readMethod = propertyDescriptor.getReadMethod();
                Object value = readMethod.invoke(this);
                map.put(StringUtils.snakeCase(key), value);
            }
        } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
            log.error("", e);
        }

        return map;
    }
}
